
#include <stdlib.h>
#include <GL/glut.h>
#include <iostream>

#include "extrusion.h"
#include "Figure.h"
#include "Trajectory.h"

#define CONCAVE -1
#define CONVEX 1

using namespace std ;

extrusion::extrusion()
{
	red=0.0;
	green=0.0;
	blue=1.0;
	CCW=false;
	indSize=0;
	numShape=0;
	numTraj=0;
}

void extrusion::renderextrusion() 
{

	 glEnableClientState(GL_VERTEX_ARRAY);

	 glVertexPointer(3, GL_FLOAT, 0, vertexes);

	 glDrawElements(GL_QUADS, indSize, GL_UNSIGNED_INT, indexes);

	 glDisableClientState(GL_VERTEX_ARRAY);


}

// Stores the extrusion
void extrusion::save( std::ostream& output )
{

}

int extrusion::checkClockWise()
{
	int con=Convex();
	if(con=CONCAVE)
	{
	
		for (int i=0;i<numShape-1;i++)
		{
		
			int a= (shape[i].x*shape[i+1].y)-(shape[i+1].x*shape[i].y);
			if(a>0)CCW=true;
		}
	}
	else if(con=CONVEX)
	{
		
		int i=1;
		int crossproduct=((shape[i].x-shape[i-1].x)*(shape[i+1].y-shape[i].y))-((shape[i].y-shape[i-1].y)*(shape[i+1].x-shape[i].x));
		if(crossproduct>0)CCW=true;
		
	}
	else 	return -1;
	return 0;

}
int extrusion::invertClockWise()
{
	if(CCW==true){return 0;}
	else
	{
		
		
		auxiliar=shape;

		shape.clear();
		while(auxiliar.size()>0)
		{
			shape.push_back(auxiliar.back());
			auxiliar.pop_back();
		}

		
		return 0;

		
	}
}
void extrusion::load(Figure *fig, Trajectory* traj)
{

	numShape = fig->_vertices.size();
	numTraj = traj->_vertices.size();


	shape=fig->_vertices;
	trajectory=traj->_vertices;

	checkClockWise();
	invertClockWise();

	vertexes=new GLfloat[numShape*3*numTraj];

	indSize=numShape*4*(numTraj-1);

	indexes=new GLuint[indSize];

	int i=0;
	for(int tra=0;tra<numTraj;tra++)
	{	
		for(int sha=0;sha<numShape;sha++)
		{
				
				vertexes[i]=shape[sha].x+trajectory[tra].x;
				vertexes[i+1]=trajectory[tra].y;
				vertexes[i+2]=shape[sha].y;
				i+=3;
			
			
		}
	}

	
	for(int j=0,shape=0;j<numShape*(numTraj-1)*4,shape<(numShape*numTraj-numShape);j+=4,shape++)
	{
		if((shape%numShape)!=0)
		{
			indexes[j]=shape;
			indexes[j+1]=shape+numShape;
			indexes[j+2]=shape+numShape-1;
			indexes[j+3]=shape-1;
		}
		else
		{
			indexes[j]=shape;
			indexes[j+1]=shape+numShape;
			indexes[j+2]=shape+numShape+numShape-1;
			indexes[j+3]=shape+numShape-1;
			

		}


	}

	
	
}



int extrusion::Convex()
{
   int i,j,k;
   int flag = 0;
   double z;

   if (numShape < 3)
      return(0);

   for (i=0;i<numShape;i++) {
      j = (i + 1) % numShape;
      k = (i + 2) % numShape;
      z  = (shape[j].x - shape[i].x) * (shape[k].y - shape[j].y);
      z -= (shape[j].y - shape[i].y) * (shape[k].x - shape[j].x);
      if (z < 0)
         flag |= 1;
      else if (z > 0)
         flag |= 2;
      if (flag == 3)
         return(CONCAVE);
   }
   if (flag != 0)
      return(CONVEX);
   else
      return(0);
}
